/*
 * Copyright (c) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the 'License');
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an 'AS IS' BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import { cert } from '@kit.DeviceCertificateKit';

/**
 * X509TrustManager 接口定义
 * 
 * 注意：鸿蒙的 TLS 证书验证由底层 socket API 自动处理。
 * 此接口主要用于控制是否跳过远程证书验证（仅用于测试环境）。
 */
export interface X509TrustManager {
  /**
   * 是否跳过远程证书验证
   * 警告：生产环境中应始终为 false
   */
  skipRemoteValidation: boolean;

  /**
   * 验证客户端证书（服务端调用，客户端一般不使用）
   * @param data 证书数据
   */
  checkClientTrusted?(data: cert.EncodingBlob): void | Promise<void>;

  /**
   * 验证服务器证书
   * @param data 证书数据
   */
  checkServerTrusted?(data: cert.EncodingBlob): void | Promise<void>;
}

/**
 * 系统默认的 X509TrustManager 实现
 * 使用系统信任的 CA 证书进行验证（由鸿蒙底层处理）
 */
export class X509TrustManagerSystem implements X509TrustManager {
  static SYSTEM: X509TrustManager = new X509TrustManagerSystem();
  skipRemoteValidation: boolean = false;

  /**
   * 验证客户端证书
   * 客户端模式下通常不需要，由鸿蒙底层处理
   */
  async checkClientTrusted(_data: cert.EncodingBlob): Promise<void> {
    // 鸿蒙底层自动处理
  }

  /**
   * 验证服务器证书
   * 由鸿蒙底层自动处理，此方法仅作为接口兼容
   */
  async checkServerTrusted(_data: cert.EncodingBlob): Promise<void> {
    // 鸿蒙底层自动处理
  }
}
